package com.haitonghop.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import com.haitonghop.main.DisplayUtils;

import android.app.Activity;
import android.app.ProgressDialog;
import android.app.WallpaperManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.os.Environment;
import android.os.StatFs;
import android.widget.Toast;

public class Utils {
	public static boolean sdCardMounted2() {
		try {
			if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
				return true;
			}
		} catch (Exception e) {
		}
		return false;
	}

	public static boolean sdCardAvailableSpace() {
		// the statistics of the SD card
		StatFs stats;
		long freeSpace;
		// set the number format output
		// NumberFormat numberFormat;

		if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)
				|| android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_UNMOUNTED)
				|| android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED_READ_ONLY)) {
			// obtain the stats from the root of the SD card.
			stats = new StatFs(Environment.getExternalStorageDirectory().getPath());

			long availableBlocks = stats.getAvailableBlocks();
			long blockSize = stats.getBlockSize();

			freeSpace = availableBlocks * blockSize;

			long freeSpaceMB = (freeSpace / 1048576);
			if (freeSpaceMB > 5)
				return true;
			else
				return false;
		}
		return false;
	}

	public static void sendEmail(Activity activity) {
		if (activity != null) {
			Intent i = new Intent(Intent.ACTION_SEND);
			i.setType("message/rfc822");
			i.putExtra(Intent.EXTRA_EMAIL, new String[] { "thanhle.hoangthanh0@gmail.com" });
			i.putExtra(Intent.EXTRA_SUBJECT, "Feedback SunnyPlace");
			i.putExtra(Intent.EXTRA_TEXT, "");
			try {
				activity.startActivity(Intent.createChooser(i, "Send mail..."));
			} catch (android.content.ActivityNotFoundException ex) {
				Toast.makeText(activity, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
			}
		}
	}

	public static String getExternalStorageDirectory() {
		String zaloFolder = "/HaiBua/";
		String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
		File myNewFolder = new File(extStorageDirectory + zaloFolder);
		myNewFolder.mkdir();
		return extStorageDirectory + zaloFolder;
	}

	public static String getPictureExternalStorageDirectory() {
		getExternalStorageDirectory();

		String zaloFolder = "/HaiBua/Images/";
		String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
		File myNewFolder = new File(extStorageDirectory + zaloFolder);
		myNewFolder.mkdir();
		return extStorageDirectory + zaloFolder;
	}

	public static boolean isExist(String filename) {
		File check = new File(filename);
		return check.exists();
	}

	public static void downloadPhoto(final Context context, final int position, final Activity activity, final String src, final Resources resources) {
		final ProgressDialog loadingDialog = new ProgressDialog(context);
		loadingDialog.setCancelable(true);
		loadingDialog.setCanceledOnTouchOutside(false);
		loadingDialog.setMessage("Đang tải ảnh về máy!");
		loadingDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		if (!Utils.sdCardMounted2()) {
			DisplayUtils.showMess("Không tìm thấy thẻ nhớ", activity);
			return;
		}

		if (!Utils.sdCardAvailableSpace()) {
			DisplayUtils.showMess("Thẻ nhớ đầy", activity);
			return;
		}

		loadingDialog.setMessage("Đang tải ảnh về máy!");
		if (loadingDialog != null && !loadingDialog.isShowing() && !activity.isFinishing())
			loadingDialog.show();

		new Thread(new Runnable() {
			public void run() {
				try {

					String path = GlobalData.mAQ.getCachedFile(src).getAbsolutePath();
					String name = StringUtils.MD5(src);
					String desPath = getPictureExternalStorageDirectory() + name + ".jpg";

					if (!Utils.isExist(desPath)) {
						File f1 = new File(path);
						File f2 = new File(desPath);
						InputStream in = new FileInputStream(f1);

						// For Append the file.
						// OutputStream out = new FileOutputStream(f2,true);

						// For Overwrite the file.
						OutputStream out = new FileOutputStream(f2);

						byte[] buf = new byte[1024];
						int len;
						while ((len = in.read(buf)) > 0) {
							out.write(buf, 0, len);
						}
						in.close();
						out.close();

						DisplayUtils.showMess("Ảnh được lưu ở: " + desPath, activity);
					} else {
						DisplayUtils.showMess("Ảnh được lưu ở: " + desPath, activity);
					}

					if (loadingDialog != null && loadingDialog.isShowing() && !activity.isFinishing())
						loadingDialog.dismiss();
				} catch (Exception e) {
					DisplayUtils.showMess("Có lỗi xảy ra, vui lòng thử lại sau.", activity);
					// saveImageToGallery(path, name + ".jpg");
				}
			}
		}).start();
	}

	public static void setWallpaper(final Context context, final int position, final Activity activity, final String src, final Resources resources) {
		final ProgressDialog loadingDialog = new ProgressDialog(context);
		loadingDialog.setCancelable(true);
		loadingDialog.setCanceledOnTouchOutside(false);
		loadingDialog.setMessage("Đang tạo ảnh nền!");
		loadingDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		try {
			loadingDialog.setMessage("Đang tạo ảnh nền!");
			if (loadingDialog != null && !loadingDialog.isShowing() && !activity.isFinishing())
				loadingDialog.show();

			new Thread(new Runnable() {
				public void run() {
					try {

						WallpaperManager myWallpaperManager = WallpaperManager.getInstance(context);

						// create scaled bitmap to fit screen
						Bitmap oldBM = GlobalData.mAQ.getCachedImage(src);

						if (oldBM == null) {
							File file = GlobalData.mAQ.getCachedFile(src);
							if (file != null && file.exists()) {
								oldBM = BitmapFactory.decodeFile(GlobalData.mAQ.getCachedFile(src).getAbsolutePath());
							} else {
								if (loadingDialog != null && loadingDialog.isShowing() && !activity.isFinishing())
									loadingDialog.dismiss();

								DisplayUtils.showMess("Có lỗi xảy ra, vui lòng thử lại sau.", activity);
								return;
							}
						}

						float ratio = (float) oldBM.getHeight() / (float) oldBM.getWidth();
						int w = resources.getDisplayMetrics().widthPixels;
						int h = (int) (w * ratio);

						Bitmap bm = Bitmap.createScaledBitmap(GlobalData.mAQ.getCachedImage(src), w, h, true);

						if (oldBM != null && !oldBM.isRecycled()) {
							oldBM.recycle();
							oldBM = null;
						}

						int newW = myWallpaperManager.getDesiredMinimumWidth();
						int newH = myWallpaperManager.getDesiredMinimumHeight();

						if (newW > 0 && newH > 0) {
							Bitmap resultBM = Bitmap.createBitmap(newW, newH, bm.getConfig());
							Canvas canvas = new Canvas(resultBM);
							canvas.drawBitmap(bm, (resultBM.getWidth() / 2) - (bm.getWidth() / 2), (resultBM.getHeight() / 2) - (bm.getHeight() / 2), null);
							myWallpaperManager.setBitmap(resultBM);

							if (bm != null && !bm.isRecycled()) {
								bm.recycle();
								bm = null;
							}

							if (resultBM != null && !resultBM.isRecycled()) {
								resultBM.recycle();
								resultBM = null;
							}
						} else {
							myWallpaperManager.setBitmap(bm);

							if (bm != null && !bm.isRecycled()) {
								bm.recycle();
								bm = null;
							}
						}

						if (bm != null && !bm.isRecycled())
							bm.isRecycled();

						if (loadingDialog != null && loadingDialog.isShowing() && !activity.isFinishing())
							loadingDialog.dismiss();

						DisplayUtils.showMess("Hình nền đã được cài đặt lên màn hình.", activity);
					} catch (Exception e) {
						e.printStackTrace();

						if (loadingDialog != null && loadingDialog.isShowing() && !activity.isFinishing())
							loadingDialog.dismiss();

						DisplayUtils.showMess("Có lỗi xảy ra, vui lòng thử lại sau.", activity);
					}
				}
			}).start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
